/**
 * Created by chengys
 */

package fyp.spedmew;

import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.text.ParseException;
import java.util.List;

import fyp.spedmew.backend.entity.checkInEndpoint.model.CheckIn;
import fyp.spedmew.backend.entity.jobEndpoint.model.Job;
import fyp.spedmew.connector.CheckInInsertATask;
import fyp.spedmew.connector.JobInsertATask;

public class DispatcherDetailActionBarActivity extends ActionBarActivity {

    private Bundle jobData = new Bundle();
    private String title, desc, shipDate, price, pic;
    private String pickupLoc, deliveryLoc, recipientNo, customInstruction,id ;
    private Uri image;
    private static final String TAG = new Object(){}.getClass().getCanonicalName();
    private Button btnFusedLocation;
    private TextView tvLocation;
    private FusedLocationService fusedLocationService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobsummarywithupdatelocation);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent in = getIntent();
        jobData = in.getExtras();

        title = jobData.getString("name");
        desc = jobData.getString("descr");
        shipDate = jobData.getString("date");
        price = jobData.getString("price");
        pic = jobData.getString("pic");
        pickupLoc = jobData.getString("pickupLoc");
        deliveryLoc = jobData.getString("dropoffLoc");
        recipientNo = jobData.getString("recipientNo");
        customInstruction = jobData.getString("customIns");
        id =jobData.getString("id");
       // image = Uri.parse( jobData.getString("pic"));
        image = Uri.parse( "pic1");
        ImageView imageView = (ImageView) findViewById(R.id.SimgView);
        imageView.setImageURI(image);

        ((TextView)findViewById(R.id.nameTxt)).setText(title);
        ((TextView)findViewById(R.id.descTxt)).setText(desc);
        ((TextView)findViewById(R.id.dateTxt)).setText(shipDate);
        ((TextView)findViewById(R.id.priceTxt)).setText(price);
        ((TextView)findViewById(R.id.pickupTxt)).setText(pickupLoc);
        ((TextView)findViewById(R.id.dropoffTxt)).setText(deliveryLoc);
        ((TextView)findViewById(R.id.recipientTxt)).setText(recipientNo);
        ((TextView)findViewById(R.id.customTxt)).setText(customInstruction);





        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        fusedLocationService = new FusedLocationService(this);
        tvLocation = (TextView) findViewById(R.id.tvLocation);
        btnFusedLocation = (Button) findViewById(R.id.btnGPSShowLocation);
        btnFusedLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Location location = fusedLocationService.getLocation();
                String locationResult = "";
                if (null != location) {
                    Log.i(TAG, location.toString());
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    float accuracy = location.getAccuracy();
                    double elapsedTimeSecs = (double) location.getElapsedRealtimeNanos()
                            / 1000000000.0;
                    String provider = location.getProvider();
                    double altitude = location.getAltitude();
                    locationResult = "Latitude: " + latitude + "\n" +
                            "Longitude: " + longitude + "\n" +
                            "Altitude: " + altitude + "\n" +
                            "Accuracy: " + accuracy + "\n" +
                            "Elapsed Time: " + elapsedTimeSecs + " secs" + "\n" +
                            "Provider: " + provider + "\n";

                    //TODO: Replace this dummy job id asap
                    String dummyJobId = "1";
                    saveCheckIntoDB(dummyJobId, location.getLatitude(), location.getLongitude());


                } else {
                    locationResult = "Location Not Available!";
                }
                tvLocation.setText(locationResult);


            }
        });

        final Button btn = (Button) findViewById(R.id.req_btn);
        btn.setBackgroundColor(getResources().getColor(R.color.button_BG_OnPressed));

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                btn.setBackgroundColor(getResources().getColor(R.color.button_BG));
            }
        }, 300);

        btn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                LayoutInflater inflater = getLayoutInflater();

                View layout = inflater.inflate(R.layout.toast_pop_up,
                        (ViewGroup) findViewById(R.id.custom_toast_layout_id));

                // set a message
                TextView text = (TextView) layout.findViewById(R.id.text);
               text.setText("Request Sent");

                ParseObject Verify = new ParseObject("Verify");


                Verify.put("JobID", id);
                Verify.put("Verify", "tesdfsd");
          //      P_Location.put("Latitude",location.getLatitude() );
         //       P_Location.put("Longitude",location.getLongitude() );
                Verify.saveInBackground();


                // Toast...
                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_create__shipment5, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void saveToDB(Job job)
    {
        new JobInsertATask().execute(job);
    }

    private void saveToStatusToDB(Job job)
    {
        new JobInsertATask().execute(job);
    }

    public void sendMessage(View view) {
        EditText instructionsET = (EditText) findViewById(R.id.Verifytxt );
           String Check= instructionsET.getText().toString();

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_pop_up,
                (ViewGroup) findViewById(R.id.custom_toast_layout_id));

        // set a message
        TextView text = (TextView) layout.findViewById(R.id.text);




if (Check.equals("12345") ){

    text.setText("Ok");


}else {text.setText("fail");}
        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Verify");
       // query.whereEqualTo("JobID", id.toString() );
        query.findInBackground(new FindCallback<ParseObject>() {
                                   public void done(List<ParseObject> Verify, ParseException e) {
                                       if (e == null) {

                                           if (Verify == null){



                                           } else {
                                               LayoutInflater inflater = getLayoutInflater();
                                               View layout = inflater.inflate(R.layout.toast_pop_up,
                                                       (ViewGroup) findViewById(R.id.custom_toast_layout_id));

                                               // set a message
                                               TextView text = (TextView) layout.findViewById(R.id.text);

                                               EditText instructionsET = (EditText) findViewById(R.id.Verifytxt );
                                             if (Verify.get(0).getString("Verify").equals(instructionsET.getText().toString())){
                                                 text.setText("OK");
                                                 Toast toast = new Toast(getApplicationContext());
                                                 toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                                                 toast.setDuration(Toast.LENGTH_LONG);
                                                 toast.setView(layout);
                                                 toast.show();

                                             }else{  text.setText("fail");}
                                               Toast toast = new Toast(getApplicationContext());
                                               toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                                               toast.setDuration(Toast.LENGTH_LONG);
                                               toast.setView(layout);
                                               toast.show();
                                           }


                                       }

                                   }

            @Override
            public void done(List<ParseObject> parseObjects, com.parse.ParseException e) {

            }
        });




        // set a message




    }


    private void saveCheckIntoDB(String jobId, Double latitude, Double longitude) {
        CheckIn checkIn = new CheckIn();
        checkIn.setJobId(Long.valueOf(jobId));
        checkIn.setLat(latitude);
        checkIn.setLong(longitude);
        new CheckInInsertATask().execute(checkIn);
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }
}
 